<template>
  <view class="container">
    <form @submit="submitForm">
      <view class="form-item">
        <view class="form-label">
          <text class="required">*</text>
          <text>单元选择</text>
        </view>
        <view class="selector-value" @click="showUnitSelectModal = true">
          {{ form.unit_id ? selectedUnitText : '请选择单元' }}
          <text class="arrow-icon">›</text>
        </view>
        <text v-if="errors.unit_id" class="error-message">{{ errors.unit_id }}</text>
      </view>
      
      <view class="form-item">
        <view class="form-label">
          <text class="required">*</text>
          <text>服务日期</text>
        </view>
        <picker mode="date" :value="form.expected_service_date" 
          :start="startDate" end="2030-12-31" @change="onDateChange">
          <view class="selector-value">
            {{ form.expected_service_date || '请选择日期' }}
            <text class="arrow-icon">›</text>
          </view>
        </picker>
        <text v-if="errors.expected_service_date" class="error-message">{{ errors.expected_service_date }}</text>
      </view>
      
      <view class="form-item">
        <view class="form-label">
          <text class="required">*</text>
          <text>服务时间段</text>
        </view>
        <picker :range="timeSlotOptions" range-key="label" @change="onTimeSlotChange">
          <view class="selector-value">
            {{ form.expected_time_slot || '请选择时间段' }}
            <text class="arrow-icon">›</text>
          </view>
        </picker>
        <text v-if="errors.expected_time_slot" class="error-message">{{ errors.expected_time_slot }}</text>
      </view>
      
      <view class="form-item">
        <view class="form-label">
          <text>特殊要求</text>
        </view>
        <textarea
          v-model="form.special_requirements"
          class="textarea-input"
          placeholder="请输入特殊要求或说明（可选）"
          maxlength="200"
        ></textarea>
        <view class="textarea-counter">{{ form.special_requirements.length }}/200</view>
      </view>
    </form>
    
    <view class="notice">
      <view class="notice-title">
        <text class="info-icon">ⓘ</text>
        <text>保洁服务说明</text>
      </view>
      <view class="notice-content">
        <text>1. 保洁服务需提前至少24小时预约</text>
        <text>2. 服务时间为每日8:00-17:00</text>
        <text>3. 特殊需求可在备注中说明</text>
        <text>4. 保洁服务费用将在服务完成后收取</text>
      </view>
    </view>
    
    <!-- 单元选择弹窗 -->
    <view v-if="showUnitSelectModal" class="custom-popup-mask" @click="showUnitSelectModal = false">
      <view class="custom-popup" @click.stop>
        <view class="popup-header">
          <text class="popup-title">选择单元</text>
          <text class="popup-close" @click="showUnitSelectModal = false">×</text>
        </view>
        <scroll-view scroll-y class="popup-body">
          <view v-if="loadingUnits" class="loading-container">
            <text>加载中...</text>
          </view>
          <view v-else-if="unitList.length === 0" class="empty-container">
            <text>暂无可用单元</text>
          </view>
          <view
            v-else
            v-for="(item, index) in unitList"
            :key="index"
            class="popup-item"
            @click="selectUnit(item)"
          >
            <text>{{ item.building_name }} {{ item.floor_label }} {{ item.unit_number }}</text>
          </view>
        </scroll-view>
      </view>
    </view>
    
    <view class="btn-wrapper">
      <button class="submit-btn" @click="submitForm">提交预约</button>
    </view>
  </view>
</template>

<script>
import { createCleaningBooking, getUserAvailableUnits } from '@/api/services'
import eventBus from '@/utils/eventBus.js'

export default {
  data() {
    const today = new Date()
    const year = today.getFullYear()
    const month = String(today.getMonth() + 1).padStart(2, '0')
    const day = String(today.getDate()).padStart(2, '0')
    
    return {
      form: {
        unit_id: '',
        expected_service_date: '',
        expected_time_slot: '',
        special_requirements: ''
      },
      errors: {
        unit_id: '',
        expected_service_date: '',
        expected_time_slot: ''
      },
      unitList: [],
      loadingUnits: false,
      timeSlotOptions: [
        { value: '08:00-10:00', label: '上午 08:00-10:00' },
        { value: '10:00-12:00', label: '上午 10:00-12:00' },
        { value: '13:00-15:00', label: '下午 13:00-15:00' },
        { value: '15:00-17:00', label: '下午 15:00-17:00' }
      ],
      showUnitSelectModal: false,
      selectedUnitText: '',
      startDate: `${year}-${month}-${day}`,
      userId: null
    }
  },
  onLoad() {
    this.getUserInfo()
  },
  onReady() {
    this.loadUserUnits()
  },
  methods: {
    // 加载用户的单元列表
    loadUserUnits() {
      this.loadingUnits = true
      console.log('开始加载用户单元列表...')
      
      getUserAvailableUnits()
        .then(units => {
          console.log('获取到的用户单元列表 (详细):', JSON.stringify(units, null, 2))
          
          if (!units || units.length === 0) {
            console.log('警告：后端返回空单元列表')
            // 使用模拟数据进行测试
            this.unitList = [
              {
                unit_id: 100,
                unit_number: 'TEST-101',
                building_name: '测试楼栋',
                floor_label: '1层'
              }
            ]
            uni.showToast({
              title: '使用测试数据 (未找到单元)',
              icon: 'none'
            })
          } else {
            this.unitList = units
          }
        })
        .catch(error => {
          console.error('获取用户单元列表失败 (详细错误):', error)
          uni.showToast({
            title: '获取单元列表失败: ' + (error.message || '未知错误'),
            icon: 'none'
          })
          
          // 出错时使用简单的模拟数据
          this.unitList = [
            {
              unit_id: 999,
              unit_number: 'ERROR-101',
              building_name: '错误数据',
              floor_label: '1层'
            }
          ]
        })
        .finally(() => {
          this.loadingUnits = false
          console.log('最终使用的单元列表:', JSON.stringify(this.unitList, null, 2))
        })
    },
    
    // 选择单元
    selectUnit(unit) {
      this.form.unit_id = parseInt(unit.unit_id, 10)
      this.selectedUnitText = `${unit.building_name} ${unit.floor_label} ${unit.unit_number}`
      this.showUnitSelectModal = false
      this.errors.unit_id = ''
    },
    
    // 日期选择
    onDateChange(e) {
      this.form.expected_service_date = e.detail.value
      this.errors.expected_service_date = ''
    },
    
    // 时间段选择
    onTimeSlotChange(e) {
      const index = e.detail.value
      this.form.expected_time_slot = this.timeSlotOptions[index].value
      this.errors.expected_time_slot = ''
    },
    
    // 表单验证
    validateForm() {
      let isValid = true
      
      // 重置错误信息
      this.errors = {
        unit_id: '',
        expected_service_date: '',
        expected_time_slot: ''
      }
      
      if (!this.form.unit_id) {
        this.errors.unit_id = '请选择单元'
        isValid = false
      }
      
      if (!this.form.expected_service_date) {
        this.errors.expected_service_date = '请选择服务日期'
        isValid = false
      }
      
      if (!this.form.expected_time_slot) {
        this.errors.expected_time_slot = '请选择服务时间段'
        isValid = false
      }
      
      return isValid
    },
    
    // 提交表单
    submitForm() {
      if (!this.userId) {
        uni.showToast({
          title: '用户未登录，请先登录',
          icon: 'none'
        })
        return
      }
      
      if (this.validateForm()) {
        uni.showLoading({ title: '提交中...' })
        
        // 确保表单数据格式正确
        const formData = {
          unit_id: parseInt(this.form.unit_id, 10),
          expected_service_date: this.form.expected_service_date,
          expected_time_slot: this.form.expected_time_slot,
          special_requirements: this.form.special_requirements || '',
          applicant_user_id: this.userId
        }
        
        console.log('Submitting form data:', formData)
        
        createCleaningBooking(formData)
          .then(() => {
            uni.showToast({
              title: '预约成功',
              icon: 'success'
            })
            
            // 发射刷新事件，通知列表页刷新
            eventBus.emit('refreshCleaningList')
            
            // 返回列表页并传递刷新标志
            setTimeout(() => {
              // 使用navigateBack返回，事件总线会通知列表页刷新
              uni.navigateBack()
            }, 1500)
          })
          .catch(err => {
            uni.showToast({
              title: '预约失败：' + err.message,
              icon: 'none'
            })
          })
          .finally(() => {
            uni.hideLoading()
          })
      }
    },
    getUserInfo() {
      const userInfo = uni.getStorageSync('userInfo')
      if (userInfo && userInfo.userId) {
        this.userId = userInfo.userId
        console.log('Current user ID:', this.userId)
      } else {
        console.error('User ID not found in storage')
        uni.showToast({
          title: '用户信息获取失败，请重新登录',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  padding: 30rpx;
}

.form-item {
  margin-bottom: 30rpx;
}

.form-label {
  display: flex;
  font-size: 28rpx;
  margin-bottom: 16rpx;
  
  .required {
    color: #f56c6c;
    margin-right: 4rpx;
  }
}

.selector-value {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 80rpx;
  padding: 0 20rpx;
  border: 1px solid #e4e7ed;
  border-radius: 4rpx;
  color: #666;
}

.arrow-icon {
  font-size: 36rpx;
  transform: rotate(90deg);
  color: #999;
}

.textarea-input {
  width: 100%;
  height: 240rpx;
  border: 1px solid #e4e7ed;
  border-radius: 4rpx;
  padding: 20rpx;
  font-size: 28rpx;
  box-sizing: border-box;
}

.textarea-counter {
  text-align: right;
  font-size: 24rpx;
  color: #999;
  margin-top: 8rpx;
}

.error-message {
  font-size: 24rpx;
  color: #f56c6c;
  margin-top: 8rpx;
}

.notice {
  margin-top: 40rpx;
  padding: 20rpx;
  background-color: #f8f9fa;
  border-radius: 12rpx;
  margin-bottom: 80rpx;
}

.notice-title {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
  font-size: 30rpx;
  font-weight: bold;
}

.info-icon {
  color: #3c9cff;
  margin-right: 8rpx;
  font-size: 36rpx;
}

.notice-content {
  display: flex;
  flex-direction: column;
  color: #666;
  font-size: 28rpx;
}

.notice-content text {
  margin-bottom: 10rpx;
}

.custom-popup-mask {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 9999;
  display: flex;
  align-items: flex-end;
}

.custom-popup {
  width: 100%;
  background-color: #fff;
  border-radius: 24rpx 24rpx 0 0;
  overflow: hidden;
  animation: slideUp 0.3s ease;
}

@keyframes slideUp {
  from {
    transform: translateY(100%);
  }
  to {
    transform: translateY(0);
  }
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1px solid #eee;
}

.popup-title {
  font-size: 32rpx;
  font-weight: bold;
}

.popup-close {
  font-size: 40rpx;
  color: #999;
}

.popup-body {
  max-height: 600rpx;
}

.popup-item {
  padding: 30rpx;
  border-bottom: 1px solid #f5f5f5;
  font-size: 28rpx;
}

.btn-wrapper {
  padding: 30rpx 0;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  padding: 30rpx;
}

.submit-btn {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  text-align: center;
  background-color: #3c9cff;
  color: #ffffff;
  font-size: 32rpx;
  border-radius: 8rpx;
  border: none;
}

/* 添加加载中和空数据状态的样式 */
.loading-container,
.empty-container {
  padding: 40rpx 0;
  text-align: center;
  color: #999;
  font-size: 28rpx;
}
</style> 